package com.damai.pay.wx;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.citywithincity.utils.IoUtil;


@SuppressWarnings("deprecation")
public class WXUtil {
	public static CloseableHttpClient createHttpClient(String keyStorePath,String mchID) throws Exception {
		FileInputStream instream = null;
		instream = new FileInputStream(new File(keyStorePath));
		return createHttpClient(instream,mchID);
	}
	/**
	 * 创建双向认证的httpclient用于退款
	 * @param keyStorePath
	 * @param mchID
	 * @return
	 * @throws IOException 
	 * @throws CertificateException 
	 * @throws NoSuchAlgorithmException 
	 */
	public static CloseableHttpClient createHttpClient(InputStream instream,String mchID){
		try{
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			
			keyStore.load(instream, mchID.toCharArray());
			instream.close();
			// Trust own CA and all self-signed certs
			SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchID.toCharArray()).build();
			// Allow TLSv1 protocol only
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
					sslcontext,
					new String[] { "TLSv1" },
					null,
					SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		}catch(Exception e){
			return null;
		}finally {
			IoUtil.close(instream);
		}
		

	}
	
	
	
	
}
